package com.zzg.lucene;

import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.DoublePoint;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;

public class SearchDoublePoint {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		Directory directory = new RAMDirectory();
	    IndexWriter indexWriter = new IndexWriter(directory, new IndexWriterConfig(new StandardAnalyzer()));
	    Document document = new Document();
	    Field doublePoint = new DoublePoint("age", 11.1);
	    document.add(doublePoint);
	    doublePoint = new StoredField("age", 11.1);
	    document.add(doublePoint);
	    indexWriter.addDocument(document);
	    doublePoint = new DoublePoint("age", 22.2);
	    document = new Document();
	    document.add(doublePoint);
	    doublePoint = new StoredField("age", 22.2);
	    document.add(doublePoint);
	    indexWriter.addDocument(document);
	    indexWriter.close();
	    IndexSearcher indexSearcher = new IndexSearcher(DirectoryReader.open(directory));
	    //精确查询
	    Query query = DoublePoint.newExactQuery("age", 11.1);
	    ScoreDoc[] scoreDocs = indexSearcher.search(query, 10).scoreDocs;
	    for (ScoreDoc scoreDoc : scoreDocs) {
	        System.out.println("精确查询：" + indexSearcher.doc(scoreDoc.doc));
	    }
	    //范围查询，不包含边界
	    query = DoublePoint.newRangeQuery("age", Math.nextUp(11.1), Math.nextDown(22.2));
	    scoreDocs = indexSearcher.search(query, 10).scoreDocs;
	    for (ScoreDoc scoreDoc : scoreDocs) {
	        System.out.println("不包含边界：" + indexSearcher.doc(scoreDoc.doc));
	    }
	    //范围查询，包含边界
	    query = DoublePoint.newRangeQuery("age", 11.1, 22.2);
	    scoreDocs = indexSearcher.search(query, 10).scoreDocs;
	    for (ScoreDoc scoreDoc : scoreDocs) {
	        System.out.println("包含边界：" + indexSearcher.doc(scoreDoc.doc));
	    }
	    //范围查询，左包含，右不包含
	    query = DoublePoint.newRangeQuery("age", 11.1, Math.nextDown(22.2));
	    scoreDocs = indexSearcher.search(query, 10).scoreDocs;
	    for (ScoreDoc scoreDoc : scoreDocs) {
	        System.out.println("左包含右不包含：" + indexSearcher.doc(scoreDoc.doc));
	    }
	    //集合查询
	    query = DoublePoint.newSetQuery("age", 11.1, 22.2, 33.3);
	    scoreDocs = indexSearcher.search(query, 10).scoreDocs;
	    for (ScoreDoc scoreDoc : scoreDocs) {
	        System.out.println("集合查询：" + indexSearcher.doc(scoreDoc.doc));
	    }
	}

}
